package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"seichat/biz"
	"seichat/middlerware"
	"seichat/service"
	"seichat/types"
	"strconv"
)

type user struct {
	Name     string
	Avatar   string
	Gender   string
	Phone    string
	Email    string
	Identity string
}

type RelationHandler struct {
	relationSvc service.RelationService
}

func NewRelationHandler(relationSvc service.RelationService) *RelationHandler {
	return &RelationHandler{
		relationSvc: relationSvc,
	}
}

func (r *RelationHandler) RegisterRoutes(router *gin.Engine) {
	u := router.Group("/relation")
	{
		u.Use(middlerware.JWT())
		u.GET("/friendliest/:id", r.GetFriendListByUserId)
		u.POST("/add", r.AddFriend)
		u.POST("/addByUserName", r.AddFriendByUserName)
	}
}
func (r *RelationHandler) AddFriend(ctx *gin.Context) {
	var req types.AddFriendReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, biz.RequestParamError)
		return
	}
	if req.TargetId <= 0 {
		ctx.JSON(http.StatusBadRequest, biz.RequestParamError)
	}
	if req.UserId == req.TargetId {
		ctx.JSON(http.StatusBadRequest, biz.UserIdEqualTargetId)
		return
	}
	err := r.relationSvc.AddFriend(context.Background(), req)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, biz.InternalServerError)
		return
	}
	ctx.JSON(http.StatusOK, biz.Success(200, "添加好友成功", nil))
}

// GetFriendListByUserId 根据用户Id获取对应的好友列表
func (r *RelationHandler) GetFriendListByUserId(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, biz.InternalServerError)
	}
	users, err := r.relationSvc.GetFriendListByUserId(context.Background(), uint(id))
	if err != nil {
		zap.S().Info("获取好友列表失败", err)
		ctx.JSON(200, biz.Fail(400, "获取好友列表失败"))
		return
	}
	infos := make([]user, 0)
	for _, v := range users {
		info := user{
			Name:     v.Name,
			Avatar:   v.Avatar,
			Gender:   v.Gender,
			Phone:    v.Phone,
			Email:    v.Email,
			Identity: v.Identity,
		}
		infos = append(infos, info)
	}
	biz.RespList(ctx, 0, infos, len(infos))
}

// AddFriendByUserName 通过昵称加好友
func (r *RelationHandler) AddFriendByUserName(ctx *gin.Context) {
	var q types.AddFriendByUserNameReq
	err := ctx.ShouldBindJSON(&q)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, biz.RequestParamError)
		return
	}
	err = r.relationSvc.AddFriendByUserName(context.Background(), q)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, err)
		return
	}
	ctx.JSON(http.StatusOK, biz.Success(200, "添加好友成功", nil))
}
